<template>
  <basic-container>
    <el-row>
      <el-alert type="info" show-icon>
        <template #title>
          <el-text size="small">此 "mqtt帐号" 用于非设备类 mqtt 客户端接入，拥有超级管理员权限，需要 clientId 保证唯一，"设备"
            请按照设备三元组签名算法生成。
          </el-text>
        </template>
      </el-alert>
    </el-row>
    <el-row>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 v-model:page="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @on-load="onLoad">
        <template #menu-left>
          <el-button type="danger"
                     icon="el-icon-delete"
                     plain
                     v-if="permission.mqtt_account_delete"
                     @click="handleDelete">删 除
          </el-button>
        </template>
        <template #alert-form="{}">
          <el-alert type="info" show-icon :closable="false">
            <template #title>
              <el-text size="small">服务端不存储原始密码，请记录并妥善保管，忘记密码需重新创建。</el-text>
            </template>
          </el-alert>
        </template>
        <template #password-form="{ }">
          <el-input v-model="this.form.password" placeholder="请输入6到64个字符作为密码">
            <template #append>
              <el-button-group>
                <el-button @click="generatePassword">生成</el-button>
                <el-button v-clipboard:copy="this.form.password" v-clipboard:success="onCopySuccess">复制</el-button>
              </el-button-group>
            </template>
          </el-input>
        </template>
      </avue-crud>
      <el-dialog title="MQTT账号信息"
                 v-model="visible"
                 :close-on-click-modal="false"
                 :close-on-press-escape="false"
                 :show-close="false"
                 width="800">
        <el-row>
          <el-alert type="info" show-icon :closable="false">
            <template #title>
              <el-text size="small">服务端不存储原始密码，请记录并妥善保管，忘记密码需重新创建。</el-text>
            </template>
          </el-alert>
        </el-row>
        <el-row>
          <highlight :code="accountJson" language="json"/>
        </el-row>
        <el-row>
          <highlight :code="accountIntro" language="json" :clipboard="false"/>
        </el-row>
        <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" v-clipboard:copy="this.accountJson"
                           v-clipboard:success="copySettings">复制并关闭</el-button>
              </span>
        </template>
      </el-dialog>
    </el-row>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/iot/mqtt/account";
import {mapGetters} from "vuex";
import func from "@/utils/func";

export default {
  data() {
    const validateName = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9_\-:.@]{4,64}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('请确保您输入英文字母，并可包含数字、下划线（_）、中划线（-）、点号（.）、半角冒号（:）以及特殊字符@，整体长度需控制在4至64个字符之间'));
        return;
      }
      callback();
    };
    const validatePassword = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9_\-:.@]{6,64}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('请确保您输入英文字母，并可包含数字、下划线（_）、中划线（-）、点号（.）、半角冒号（:）以及特殊字符@，整体长度需控制在6至64个字符之间'));
        return;
      }
      callback();
    };
    return {
      form: {},
      query: {},
      loading: true,
      visible: false,
      accountJson: '',
      accountIntro: '',
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 208,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: true,
        selection: true,
        dialogWidth: 600,
        column: [
          {
            label: "",
            prop: "alert",
            type: "input",
            slot: true,
            hide: true,
            span: 24,
          },
          {
            label: "用户名",
            labelTip: "请输入英文字母，并可包含数字、下划线（_）、中划线（-）、点号（.）、半角冒号（:）以及特殊字符@，整体长度需控制在6至64个字符之间",
            prop: "username",
            search: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入用户名 6至64个字符",
              trigger: "change",
              validator: validateName
            }]
          },
          {
            label: "密码",
            labelTip: "请输入英文字母，并可包含数字、下划线（_）、中划线（-）、点号（.）、半角冒号（:）以及特殊字符@，整体长度需控制在6至64个字符之间",
            prop: "password",
            span: 24,
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [{
              required: true,
              message: "请输入密码 6至64个字符",
              trigger: "change",
              validator: validatePassword
            }]
          },
          {
            label: "签名算法",
            prop: "signMethod",
            type: "select",
            dicData: [{
              label: 'HMacMd5',
              value: 'hmacmd5'
            }, {
              label: 'HMacSha1',
              value: 'hmacsha1'
            }, {
              label: 'HMacSha256',
              value: 'hmacsha256'
            }],
            span: 24,
            rules: [{
              required: true,
              message: "请选择签名算法",
              trigger: "blur"
            }]
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.mqtt_account_add, false),
        viewBtn: this.validData(this.permission.mqtt_account_view, false),
        delBtn: this.validData(this.permission.mqtt_account_delete, false),
        editBtn: this.validData(this.permission.mqtt_account_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.accountIntro = '"username" => "非设备类客户端用于直连mqtt服务的用户名"\n' +
          '"password" =>  "非设备类客户端用于直连mqtt服务的密码"';
    },
    generatePassword() {
      this.form.password = func.strGenerate(16);
    },
    onCopySuccess() {
      this.$message.success('复制成功');
    },
    copySettings() {
      this.visible = false;
      this.$message.success('复制成功');
    },
    rowSave(row, done, loading) {
      add(row).then(res => {
        done();
        const data = res.data.data;
        this.visible = true;
        this.accountJson = JSON.stringify(data);
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "账号创建成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return remove(row.id);
      }).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
